package com.jy.appmarket.activity;

import java.util.ArrayList;
import java.util.List;

import com.jy.appmarket.R;
import com.jy.appmarket.adapter.WindowAppAdapter;
import com.jy.appmarket.adapter.WindowAppAdapter.AppClickedListener;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.model.AppInfoModel;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.WidgetNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.WidgetCacheStrategy;
import com.jy.appmarket.network.resultdata.WidgetResultData;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.statistics.event.widgetOpenEvent;
import com.jy.appmarket.statistics.umeng.myUmengStaticstics;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.FastBlur;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.utils.Prefs;
import com.jy.appmarket.utils.WidgetIconUtils;
import com.jy.appmarket.view.LoadingView;
import com.rad.statistics.android.StatisticsAgent;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WindowActivity extends DownloadActivity
		implements AppClickedListener, LoadingView.OnClickListener, NetTaskListener, OnItemClickListener {

	private static final String TAG = "WindowActivity";
	public static final String TYPE = "type";
	public static final String LIST = "list";

	public static final int ACTIVITY_RESULT = 3;
	private int mType = WidgetIconUtils.TYPE_TOOL_WIDGET;

	private GridView mGridView;
	private List<AppInfoModel> mList = null;
	private List<AppInfoModel> mRecommends = null;
	private WindowAppAdapter mAdapter;
	private TextView mTitle;
	private String mComeFrom;
	private NetTask mNetTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		Bitmap blur = getBluredBackground();
		setContentView(R.layout.activity_window_tool);
		ImageView background = findViewById(R.id.window_tool_background);
		if (blur != null) {
			background.setImageBitmap(blur);
		} else {
			background.setVisibility(View.GONE);
		}
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	private Bitmap getBluredBackground() {
		try {
			WallpaperManager wm = WallpaperManager.getInstance(this);
			BitmapDrawable d = (BitmapDrawable) wm.getDrawable();
			return FastBlur.blurBitmap(d.getBitmap());
		} catch (Exception e) {
			LogUtil.d(TAG, "failed to blur background:" + (e == null ? "" : e.getMessage()));
		}
		return null;
	}

	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = getIntent();
		if (intent.hasExtra(TYPE)) {
			mType = intent.getIntExtra(TYPE, 1);
		}
		LogUtil.d(TAG, "type:" + mType);
		myUmengStaticstics.ClickWidget(getApplicationContext(), convertType());
		StatisticsAgent.onEvent(getApplicationContext(), new widgetOpenEvent(convertType()));
		getData();
	}

	private String convertType() {
		String s = WidgetNetEngine.TYPE_TOOL;
		if (mType == WidgetIconUtils.TYPE_GAME_WIDGET) {
			s = WidgetNetEngine.TYPE_GAME;
		} else if (mType == WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET) {
			s = WidgetNetEngine.TYPE_ENTERTAINMENT;
		}
		return s;
	}

	private void getData() {
		showLoading(true);
		WidgetNetEngine engine = new WidgetNetEngine(convertType());
		mNetTask = new NetTask(this, engine, mType);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void showLoading(boolean loading) {
		LoadingView loadingview = findViewById(R.id.loading_view_layout);
		View contentview = findViewById(R.id.content_layout);

		if (loading) {
			loadingview.setVisibility(View.VISIBLE);
			loadingview.setOnClickListener(this);
			loadingview.setTextColor(Color.WHITE);
			loadingview.showWaitView(getString(R.string.ptr1_loading_wait));
			loadingview.setImage(0);
			contentview.setVisibility(View.GONE);
		} else {
			loadingview.setVisibility(View.GONE);
			contentview.setVisibility(View.VISIBLE);
		}
	}

	private void updateView() {
		mGridView = findViewById(R.id.gv_app);
		mAdapter = new WindowAppAdapter(this, this);
		mGridView.setOnItemClickListener(this);
		addFileListener(mAdapter);
		mAdapter.append(mList);
		mGridView.setAdapter(mAdapter);

		mTitle = findViewById(R.id.tv_title);

		if (mType == WidgetIconUtils.TYPE_TOOL_WIDGET) {
			mTitle.setText(this.getString(R.string.tool));
			mComeFrom = WidgetIconUtils.getWidgetTypeName(mType);
		} else if (mType == WidgetIconUtils.TYPE_GAME_WIDGET) {
			mTitle.setText(this.getString(R.string.game));
			mComeFrom = WidgetIconUtils.getWidgetTypeName(mType);
		} else if (mType == WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET) {
			mTitle.setText(this.getString(R.string.entertainment));
			mComeFrom = WidgetIconUtils.getWidgetTypeName(mType);
		}
	}

	@Override
	protected void onDestroy() {
		if (mNetTask != null) {
			mNetTask.setListener(null);
			mNetTask.cancel();
			mNetTask = null;
		}
		removeFileListener(mAdapter);
		WidgetIconUtils utils = WidgetIconUtils.getInstance();
		List<AppInfoModel> recommend = utils.trimRecommends(this, mRecommends);
		String[] user = utils.getUserSavedPackages(this, mType);
		List<AppInfoModel> list = utils.mergeWidgetList(this, recommend, user);
		switch (mType) {
		case WidgetIconUtils.TYPE_TOOL_WIDGET:
			Prefs.setEnterToolWidget(this, true);
			break;
		case WidgetIconUtils.TYPE_GAME_WIDGET:
			Prefs.setEnterGameWidget(this, true);
			break;
		case WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET:
			Prefs.setEnterEntertainmentWidget(this, true);
			break;
		}
		utils.updateIcon(this, list, mType, false);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == DeskTopAppManagerActivity.REQUEST_CODE && resultCode == Activity.RESULT_OK) {

			WidgetIconUtils utils = WidgetIconUtils.getInstance();
			List<AppInfoModel> recommend = utils.trimRecommends(this, mRecommends);
			String[] user = utils.getUserSavedPackages(this, mType);
			mList = utils.mergeWidgetList(this, recommend, user);
			List<AppInfoModel> list = new ArrayList<AppInfoModel>();
			if (mList != null && mList.size() != 0) {
				for (AppInfoModel app : mList) {
					list.add(app);
				}
			}
			utils.updateIcon(this, list, mType, false);
			mList.add(new AppInfoModel());
			updateView();
		}
	}

	@Override
	protected void onPackageInstalled(String pkgName) {
		super.onPackageInstalled(pkgName);

		if (mRecommends == null || mRecommends.size() == 0) {
			return;
		}
		String pkg = null;
		for (AppInfoModel app : mRecommends) {
			if (pkgName.equals(app.getPackageName())) {
				pkg = pkgName;
				mRecommends.remove(app);
				break;
			}
		}
		if (pkg == null || pkg.length() == 0) {
			return;
		}
		WidgetIconUtils utils = WidgetIconUtils.getInstance();
		String[] user = utils.getUserSavedPackages(this, mType);
		StringBuilder sb = new StringBuilder();
		if (user == null || user.length == 0) {
			sb.append(pkg);
		} else {
			sb.append(pkg).append("|");
			for (String s : user) {
				sb.append(s).append("|");
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		if (mType == WidgetIconUtils.TYPE_TOOL_WIDGET) {
			Prefs.saveDesktopSoftware(this, sb.toString());
		} else if (mType == WidgetIconUtils.TYPE_GAME_WIDGET) {
			Prefs.saveDesktopGame(this, sb.toString());

		} else if (mType == WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET) {
			Prefs.saveDesktopEntertainment(this, sb.toString());
		}
		user = utils.getUserSavedPackages(this, mType);
		List<AppInfoModel> recommend = utils.trimRecommends(this, mRecommends);
		mList = utils.mergeWidgetList(this, recommend, user);
		mList.add(new AppInfoModel());
		updateView();
	}

	@Override
	protected void onPackageUninstalled(String pkgName) {
		super.onPackageUninstalled(pkgName);
	}

	private void installApk(AppInfoModel app) {
		String dlId = DownloadUtils.generateDownloadId(app.getPackageName(), app.getVersionCode());
		DownloadItem dlItem = getDownloadById(dlId);
		installApk(dlItem);
	}

	@Override
	public void onAppClicked(AppInfoModel app) {
		// String id = FileDownloadService.getDownloadId(app.getPackageName());
		DownloadService dlService = getDownloadService();
		LogUtil.d(TAG, "state:" + DownloadService.getStatusString(app.getState()));

		int status = getDownloadStatus(app.getDownloadId(), app.getPackageName(), app.getVersionCode());

		switch (status) {
		case DownloadService.STATUS_INSTALLED: {
			try {
				Intent intent = getPackageManager().getLaunchIntentForPackage(app.getPackageName());
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(this, "打开失败", Toast.LENGTH_SHORT).show();
			}
		}
			break;

		case DownloadService.STATUS_CAN_INSTALL: {
			installApk(app);
		}
			break;
		case DownloadService.STATUS_DOWNLOADING: {
			if (dlService != null) {
				stopDownload(DownloadUtils.generateDownloadId(app.getPackageName(), app.getVersionCode()));
				myUmengStaticstics.stopDownload(getApplicationContext(), mComeFrom, app.getPackageName(),
						"userclick:" + status);
			} else {
				Toast.makeText(this, "系统异常，请退出重试！", Toast.LENGTH_SHORT).show();
			}
		}
			break;
		case DownloadService.STATUS_NO_STATUS: {

			startDownload(getDownloadService(), app);
			if (DownloadUtils.isMobileNetwork(this)) {
				Toast.makeText(this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
			}
		}
			break;

		case DownloadService.STATUS_PAUSED_BY_ERROR:
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
		case DownloadService.STATUS_PAUSED_BY_USER:
			// tryStartDownload(app);
			startDownload(getDownloadService(), app);
			if (DownloadUtils.isMobileNetwork(this)) {
				Toast.makeText(this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
			}
			break;
		case DownloadService.STATUS_PENDING:
			stopDownload(DownloadUtils.generateDownloadId(app.getPackageName(), app.getVersionCode()));
			myUmengStaticstics.stopDownload(getApplicationContext(), mComeFrom, app.getPackageName(),
					"userclick:" + status);
			break;

		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE:
			if (PackageUtils.isPackageInstalled(this, app.getPackageName())) { // 在widget中，已安装软件统一处理成打开
				try {
					Intent intent = getPackageManager().getLaunchIntentForPackage(app.getPackageName());
					startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(this, "打开失败", Toast.LENGTH_SHORT).show();
				}
			} else {
				// removeDownloadImmediately(app.getDownloadId());
				// removeDownloadFiles(app.getDownloadUrl());
				removeOutofDateDownloads(app.getPackageName());
				startDownload(getDownloadService(), app);
				if (DownloadUtils.isMobileNetwork(this)) {
					Toast.makeText(this, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
				}
			}
			break;

		case DownloadService.STATUS_NEED_TO_UPDATE: // 在widget中，已安装软件统一处理成打开
			try {
				Intent intent = getPackageManager().getLaunchIntentForPackage(app.getPackageName());
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(this, "打开失败", Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}
	}

	public void startDownload(DownloadService service, AppInfoModel app) {
		if (service == null) {
			return;
		}
		String dlId = DownloadUtils.generateDownloadId(app.getPackageName(), app.getVersionCode());
		DownloadItem dlItem = getDownloadById(dlId);
		if (dlItem != null) { // 之前有启动下载
			startDownload(dlId);
			myUmengStaticstics.widgetContinueDownload(getApplicationContext(), mComeFrom, dlItem.getPkgName());
		} else {
			addDownload(app.getDownloadUrl(), app.getName(), app.getPackageName(), app.getVersionName(),
					app.getVersionCode(), app.getMd5(), app.getPic(),
					new ApkSource("widget", null, null, mComeFrom).toSourceString());
			myUmengStaticstics.widgetStartDownload(getApplicationContext(), mComeFrom, app.getPackageName());
		}
	}

	private void showResult(WidgetResultData result) {
		showLoading(false);
		if (result == null) {
			mRecommends = null;
		} else {
			mRecommends = result.getList();
		}
		WidgetIconUtils utils = WidgetIconUtils.getInstance();
		List<AppInfoModel> recommend = utils.trimRecommends(this, mRecommends);
		String[] user = utils.getUserSavedPackages(this, mType);
		mList = utils.mergeWidgetList(this, recommend, user);
		mList.add(new AppInfoModel());
		updateView();
	}

	@Override
	public void onLoadingViewClick(View view) {
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		myUmengStaticstics.getNetworkDataResult(getApplicationContext(), getCommand(tag),
				engine.getResultData().getStatus() + "");

		if (!engine.getResultData().isOK()) {
			try {
				String type = getCommand(tag);
				WidgetNetEngine.restoreCache(type);
				WidgetResultData widgetResult = new WidgetResultData(type);
				WidgetCacheStrategy wcs = new WidgetCacheStrategy(type);

				widgetResult.parseResult(widgetResult.getFileContentString(wcs.getCacheFile()));
				showResult(widgetResult);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			showResult((WidgetResultData) engine.getResultData());
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		myUmengStaticstics.getNetworkDataResult(getApplicationContext(), getCommand(tag), "-1");
		try {
			LogUtil.w(TAG, "request widget error");
			String type = getCommand(tag);
			WidgetNetEngine.restoreCache(type);
			WidgetResultData widgetResult = new WidgetResultData(type);
			WidgetCacheStrategy wcs = new WidgetCacheStrategy(type);
			widgetResult.parseResult(widgetResult.getFileContentString(wcs.getCacheFile()));
			showResult(widgetResult);
		} catch (Exception e) {
			e.printStackTrace();
			showResult(null);
		}
	}

	private String getCommand(int type) {
		String s = WidgetNetEngine.TYPE_TOOL;
		if (type == WidgetIconUtils.TYPE_GAME_WIDGET) {
			s = WidgetNetEngine.TYPE_GAME;
		} else if (type == WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET) {
			s = WidgetNetEngine.TYPE_ENTERTAINMENT;
		}
		return s;
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		// nothing to do
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position == mList.size() - 1) {
			Intent intent = new Intent(this, DeskTopAppManagerActivity.class);
			intent.putExtra(WindowActivity.TYPE, mType);
			startActivityForResult(intent, DeskTopAppManagerActivity.REQUEST_CODE);
			myUmengStaticstics.widgetItemClick(getApplicationContext(), mComeFrom, "add", "0");
			return;
		} else {
			AppInfoModel aic = mList.get(position);
			if (aic.isInstalledApp()) {
				myUmengStaticstics.widgetItemClick(getApplicationContext(), mComeFrom, aic.getPackageName(),
						"installed");
				try {
					startActivity(getPackageManager().getLaunchIntentForPackage(aic.getPackageName()));
				} catch (Exception e) {
					Toast.makeText(this, "应用无法打开", Toast.LENGTH_SHORT).show();
				}
			} else {
				myUmengStaticstics.widgetItemClick(getApplicationContext(), mComeFrom, aic.getPackageName(),
						aic.getState() + "");
				onAppClicked(aic);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
